<template>
  <div class="ai-generator">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ title }}</span>
        </div>
      </template>
      <div class="content">
        <el-form :model="form" label-width="120px">
          <el-form-item :label="promptLabel">
            <el-input
              v-model="form.prompt"
              type="textarea"
              :rows="4"
              :placeholder="promptPlaceholder"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="generateContent" :loading="loading">
              生成内容
            </el-button>
          </el-form-item>
        </el-form>
        
        <div v-if="generatedContent" class="generated-content">
          <div class="content-header">
            <h3>生成结果</h3>
            <el-button type="primary" size="small" @click="saveContent">
              保存内容
            </el-button>
          </div>
          <el-input
            v-model="generatedContent"
            type="textarea"
            :rows="10"
            @input="handleContentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  promptLabel: {
    type: String,
    default: '生成提示词'
  },
  promptPlaceholder: {
    type: String,
    default: '请输入生成提示词...'
  }
})

const emit = defineEmits(['save'])

const form = ref({
  prompt: ''
})

const loading = ref(false)
const generatedContent = ref('')

const generateContent = async () => {
  if (!form.value.prompt) {
    ElMessage.warning('请输入生成提示词')
    return
  }

  loading.value = true
  try {
    const response = await axios.post('http://10.10.10.1:9999/v1/chat-messages', {
      inputs: {},
      query: form.value.prompt,
      response_mode: 'streaming',
      conversation_id: '',
      user: 'novel-writer'
    }, {
      headers: {
        'Authorization': 'Bearer app-SyclLH0E6FpO6f2xmN9zgEIP',
        'Content-Type': 'application/json'
      }
    })

    // 处理流式响应
    const reader = response.data.getReader()
    let content = ''
    
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      // 解析流式数据并更新内容
      const text = new TextDecoder().decode(value)
      const lines = text.split('\n')
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6))
            if (data.event === 'message') {
              content += data.answer
              generatedContent.value = content
            }
          } catch (e) {
            console.error('解析响应数据失败:', e)
          }
        }
      }
    }
  } catch (error) {
    console.error('生成内容失败:', error)
    ElMessage.error('生成内容失败,请重试')
  } finally {
    loading.value = false
  }
}

const handleContentChange = (value) => {
  generatedContent.value = value
}

const saveContent = () => {
  if (!generatedContent.value) {
    ElMessage.warning('没有可保存的内容')
    return
  }
  emit('save', generatedContent.value)
}
</script>

<style scoped>
.ai-generator {
  margin: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content {
  margin-top: 20px;
}

.generated-content {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.content-header h3 {
  margin: 0;
}
</style> 